package schoolmath.web.pages;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.util.TextStreamResponse;
import org.hibernate.Session;
import schoolmath.web.entities.Presentation;
import schoolmath.web.entities.User;
import schoolmath.web.entities.UserGroupUnit;
import schoolmath.web.services.UserService;

import java.util.ArrayList;
import java.util.List;

@RequiresAuthentication
public class PresentationStatus {

	@Inject
	private Request request;
	@Inject
	private Session session;
	@Inject
	private UserService userService;
	private Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

	private Presentation getPresentation(Integer id) {
		return (Presentation) session
				.createQuery("select p from Presentation p where p.id = :presentationId")
				.setParameter("presentationId", id)
				.uniqueResult();
	}

	private List<User> getListeningUsers(Presentation presentation) {
		List<User> users = new ArrayList<>();
		for (UserGroupUnit userGroupUnit : presentation.getCurrentUserGroup().getUserGroupUnits()) {
			users.add(userGroupUnit.getUser());
		}
		return users;
	}

	@CommitAfter
	private void submitProcess(Presentation presentation, Integer process) {
		presentation.setProcess(process);
		session.save(presentation);
	}

	public StreamResponse onActivate() {
		String presentationIdString = request.getParameter("presentationId");
		String presentationProcessString = request.getParameter("presentationProcess");
		Integer presentationId;
		Integer presentationProcess;
		Presentation presentation;
		boolean owner = false;

		if (presentationIdString == null) {
			return new TextStreamResponse("text/plain", "");
		}

		presentationId = Integer.valueOf(presentationIdString);
		presentation = getPresentation(presentationId);
		if (presentation == null) {
			return new TextStreamResponse("text/plain", "");
		}
		owner = presentation.getOwner().equals(userService.getUser());
		if (!owner && !getListeningUsers(presentation).contains(userService.getUser())) {
			return new TextStreamResponse("text/plain", "");
		}

		if (owner) {
			if (presentationProcessString != null) {
				presentationProcess = Integer.valueOf(presentationProcessString);
				submitProcess(presentation, presentationProcess);
			}
		}

		presentation.getOwner().setPassword("");
		if (!owner) {
			presentation.setOwner(null);
		}
		presentation.setHtml(null);
		presentation.setCurrentUserGroup(null);

		return new TextStreamResponse("text/plain", gson.toJson(presentation));
	}

}
